package com.example.mcdonaldapplication.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.mcdonaldapplication.R
import com.example.mcdonaldapplication.databinding.ActivityIntegralExchangeBinding
import com.example.mcdonaldapplication.info.GoodsInfo
import com.example.mcdonaldapplication.info.ServerIP
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

//可兑换的商品列表
class IntegralExchangeActivity : AppCompatActivity() {

    private lateinit var binding: ActivityIntegralExchangeBinding
    private val goodsList = ArrayList<GoodsInfo>()
    private val serverIp = ServerIP.getIp()
    private var uid = -1
    private var tickets = 0
    var myposition: Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityIntegralExchangeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
//        initGoods()
        getUser()
        runBlocking {
            getGoods()
            delay(800)
        }
//        getGoods()
        Log.d("goodsList",goodsList.toString())
//        val layoutManager = LinearLayoutManager(this)
        val layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        binding.integralExchangeRecyclerView.layoutManager = layoutManager
        val adapter = IntegralExchangeAdapter(goodsList)
        binding.integralExchangeRecyclerView.adapter = adapter
        binding.rule.setOnClickListener {
            val intent = Intent(this,RuleActivity::class.java)
            startActivity(intent)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getUser(){
        val prefs = getSharedPreferences("user",Context.MODE_PRIVATE)
        uid = prefs.getInt("uid",-1)
        tickets = prefs.getInt("integral",0)
        binding.myIntegral.text = "$tickets"
    }

    private fun getGoods(){
        thread {
            val formBody: FormBody = FormBody.Builder()
                .add("type", "0")
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIp}/goods/queryByType")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            Log.d("responseData",responseData)
            parseJsonGoodsExchange(responseData)
        }
    }

    private fun parseJsonGoodsExchange(json: String){
        val jsonObject = JSONObject(json)
        val data = jsonObject.getJSONArray("data")

//        Log.d("goods",goods.toString())
        for(i in 0 until data.length()){
            Log.d("good", data.get(i).toString())
            val good: JSONObject = data.get(i) as JSONObject
            val gid = good.optInt("gid")
            val price = good.optString("price")
            val content = good.optString("content")
            val name = good.optString("name")
            val type = good.optInt("type")
            val num = good.optInt("num")
            val tickets = good.optInt("tickets")
            val img = good.optString("img")
            val goodType = good.optInt("goodType")
            goodsList.add(GoodsInfo(gid,price,content,name,type,num,tickets,img,goodType))
        }
    }

    inner class IntegralExchangeAdapter(val GoodsList: List<GoodsInfo>): RecyclerView.Adapter<IntegralExchangeAdapter.ViewHolder>() {


        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
            val goods_name: TextView = view.findViewById(R.id.goods_name)
            val new_price: TextView = view.findViewById(R.id.new_price)
            val old_price: TextView = view.findViewById(R.id.old_price)
            val button: TextView = view.findViewById(R.id.exchangeBtn)
            val integral_number: TextView = view.findViewById(R.id.integralNum)
            val img: ImageView = view.findViewById(R.id.imageView2)
        }

        private var uid = -1
        private var myIntegral: Int = 0

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.goods_integral_exchange_item,parent, false)
            val prefs = parent.context.getSharedPreferences("user",Context.MODE_PRIVATE)
            uid = prefs.getInt("uid",-1)
            myIntegral = prefs.getInt("integral",0)
            return ViewHolder(view)
        }

        @SuppressLint("CommitPrefEdits", "SetTextI18n")
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val goods = GoodsList[position]
            myposition = position
            holder.goods_name.text = goods.name
            holder.old_price.text = "单买价¥${goods.price}"
            holder.integral_number.text = "${goods.tickets}"
            holder.img.drawable.level = goods.gid
            holder.button.setOnClickListener {
                if(myIntegral < goods.tickets){
                    Toast.makeText(holder.button.context,"积分不够",Toast.LENGTH_SHORT).show()
                }else if(goods.num <= 0){
                    Toast.makeText(holder.button.context,"商品没有库存啦",Toast.LENGTH_SHORT).show()
                } else{
                    runBlocking{
                        exchangeGoods(goods.gid,uid,holder.button.context)
                        val editor = holder.button.context.getSharedPreferences("user",Context.MODE_PRIVATE).edit()
                        editor.putInt("integral", myIntegral - goods.tickets)
                        myIntegral -= goods.tickets
                        editor.apply()
                        onResume()
                    }
                    Toast.makeText(holder.button.context,"兑换成功",Toast.LENGTH_SHORT).show()
                }
            }
            holder.itemView.setOnClickListener {
                exchangeOne(uid,goods.gid,goods)
            }
        }

        override fun getItemCount(): Int {
            return GoodsList.size
        }

        private fun exchangeGoods(gid: Int,uid: Int,context: Context){
            thread {
                //post方式提交的数据
                val formBody: FormBody = FormBody.Builder()
                    .add("uid", uid.toString())
                    .add("gid", gid.toString())
                    .build()
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://${serverIp}/ticket/exchangeGoods")
                    .post(formBody)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body.string()
                parseJsonExchangeByIntegral(responseData,context)
            }
        }

        private fun parseJsonExchangeByIntegral(json: String,context: Context){
            val jsonObject = JSONObject(json)
            Looper.prepare()
            Toast.makeText(context,jsonObject.optString("message"),Toast.LENGTH_SHORT).show()
            Looper.loop()
        }
    }

    fun exchangeOne(uid: Int,gid: Int,goods: GoodsInfo){
        val intent = Intent(this,ExchangeByIntegralActivity::class.java)
        intent.putExtra("uid",uid)
        intent.putExtra("gid",gid)
        intent.putExtra("sales","4000+")
        intent.putExtra("integral",goods.tickets)
        intent.putExtra("name",goods.name)
        startActivity(intent)
    }

    override fun onResume() {
        super.onResume()
        getUser()
    }
}